#include <REGX52.H>
#include "Delay.h"

unsigned char Key_KeyNumber;


unsigned char Key()
{
	unsigned char Temp=0;
	Temp = Key_KeyNumber;
	Key_KeyNumber = 0;
	return Temp;
}

/**
  * @brief  获取独立按键键码
  * @param  无
  * @retval 按下按键的键码，范围1~4，无按下为0
  */
unsigned char Key_GetState()
{
		//按下P3_1为0，松开为1,这个函数为谁按下返回几，不按返回0
		unsigned char keyNumber=0;
		if(P3_1 == 0){keyNumber = 1;}
		if(P3_0 == 0){keyNumber = 2;}
		if(P3_2 == 0){keyNumber = 3;}
		if(P3_3 == 0){keyNumber = 4;}
	
		return keyNumber;
}

//在中断中隔一段调用就可以拥有一个中断
void Key_Loop(void)
{
		//每隔20ms检测一次也可以避免抖动，而且使用中断
		static unsigned char NowState,LastState;
		LastState = NowState;
		NowState = Key_GetState();
	
		//通过改变LastState和NowState组合可以实现多种按键方式，如按下检测，长按检测等等
		if(LastState == 1 && NowState == 0)
		{
			Key_KeyNumber = 1;
		}
		if(LastState == 2 && NowState == 0)
		{
			Key_KeyNumber = 2;
		}
		if(LastState == 3 && NowState == 0)
		{
			Key_KeyNumber = 3;
		}
		if(LastState == 4 && NowState == 0)
		{
			Key_KeyNumber = 4;
		}
	
}